package com.bringspring.system.permission.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bringspring.common.annotation.JsbosTask;
import com.bringspring.common.base.Pagination;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.base.vo.DownloadVO;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.database.data.DataSourceContextHolder;
import com.bringspring.common.database.model.DataSourceModel;
import com.bringspring.common.model.login.BaseSystemInfo;
import com.bringspring.common.util.*;
import com.bringspring.common.util.enums.FileTypeEnum;
import com.bringspring.common.util.file.UploadUtil;
import com.bringspring.system.base.entity.DictionaryDataEntity;
import com.bringspring.system.base.exception.BaseException;
import com.bringspring.system.base.exception.LoginException;
import com.bringspring.system.base.service.DictionaryDataService;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.base.util.RemoveUtil;
import com.bringspring.system.external.service.SynPushToThirdQyService;
import com.bringspring.system.message.entity.SynThirdInfoEntity;
import com.bringspring.system.message.model.message.SynThirdInfoCrForm;
import com.bringspring.system.message.service.SynThirdDingTalkService;
import com.bringspring.system.message.service.SynThirdInfoService;
import com.bringspring.system.permission.constant.PermissionConst;
import com.bringspring.system.permission.entity.*;
import com.bringspring.system.permission.exception.PermissionException;
import com.bringspring.system.permission.mapper.OrganizeMapper;
import com.bringspring.system.permission.mapper.UserMapper;
import com.bringspring.system.permission.model.authorize.AuthorizeConditionModel;
import com.bringspring.system.permission.model.organize.OrganizeCrModel;
import com.bringspring.system.permission.model.user.mod.UserImportModel;
import com.bringspring.system.permission.model.user.page.PaginationUser;
import com.bringspring.system.permission.model.user.vo.UserExportExceptionVO;
import com.bringspring.system.permission.model.user.vo.UserExportVO;
import com.bringspring.system.permission.model.user.vo.UserImportVO;
import com.bringspring.system.permission.model.user.vo.UserListVO;
import com.bringspring.system.permission.service.*;
import com.bringspring.system.permission.util.BaseDataUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.Cleanup;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import static com.bringspring.system.external.constant.WxCpSysConfigConsts.SYS_DELETE;

/**
 * 用户信息
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Service
@DSTransactional
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private DataSourceModel dataSourceModel;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DictionaryDataService dictionaryDataService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Autowired
    private BaseDataUtil baseDataUtil;

    @Autowired
    private SynThirdDingTalkService synThirdDingTalkService;
    @Autowired
    private SynPushToThirdQyService synPushToThirdQyService;
    @Autowired
    private OrganizeMapper organizeMapper;

    @Autowired
    private SynThirdInfoService synThirdInfoService;


    private final static Logger logger = LoggerFactory.getLogger("sync-hr-user");
    /**
     * 取出线程池
     */
    @Autowired
    private Executor threadPoolExecutor;


    @Override
    public List<UserEntity> getList() {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<UserEntity> getUserByIds(List<String> ids) {
        List<UserEntity> list = new ArrayList<>();
        // 达梦数据库无法null值入参
        ids.removeAll(Collections.singleton(null));
        if (ids.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, ids);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<UserEntity> getUserByOrgIds(List<String> orgIds) {
        List<UserEntity> list = new ArrayList<>();
        if (orgIds.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getOrganizeId, orgIds);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<UserEntity> getUserNameList(Set<String> idList) {
        if (idList.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(UserEntity::getId, UserEntity::getRealName).in(UserEntity::getId, idList);
            return this.list(queryWrapper);
        }
        return new ArrayList<>();
    }

    @Override
    public UserEntity getByRealName(String realName) {
        UserEntity userEntity = new UserEntity();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getRealName, realName);
        queryWrapper.lambda().select(UserEntity::getId);
        List<UserEntity> list = this.list(queryWrapper);
        if (list.size() > 0) {
            userEntity = list.get(0);
        }
        return userEntity;
    }

    @Override
    public List<UserEntity> getAdminList() {
        QueryWrapper<UserEntity> query = new QueryWrapper<>();
        query.lambda().eq(UserEntity::getIsAdministrator, 1);
        query.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        return list(query);
    }

    @Override
    public List<UserEntity> getList(Pagination pagination, String organizeId, Boolean flag) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean filterLastTime = false;
        String userId = userProvider.get().getUserId();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(UserEntity::getId);

        if (flag) {
            queryWrapper.lambda().ne(UserEntity::getId, userId);
        }
        //组织机构
        if (!StringUtils.isEmpty(organizeId)) {
            List<String> orgIdList = organizeService.getUnderOrganizations(organizeId);
            PageHelper.startPage((int) pagination.getCurrentPage(), (int) pagination.getPageSize());
            // 用户id
            List<String> query = null;
            String dbSchema = "";
            // 判断是否为多租户
            if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
                dbSchema = DataSourceContextHolder.getDatasourceName();
            } else {
                dbSchema = dataSourceModel.getDbSchema();
            }
            if ("kingbasees".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryKingbase(organizeId, orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else if ("oracle".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryOracle(organizeId, orgIdList, pagination.getKeyword(), null, null);
            } else if ("dm8".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryDm(organizeId, orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else {
                query = userMapper.query(organizeId, orgIdList, pagination.getKeyword(), null, null);
            }
            PageInfo pageInfo = new PageInfo(query);
            // 赋值分页参数
            pagination.setTotal(pageInfo.getTotal());
            pagination.setCurrentPage(pageInfo.getPageNum());
            pagination.setPageSize(pageInfo.getPageSize());
            if (pageInfo.getList().size() > 0) {
                // 存放返回结果
                List<UserEntity> entityList = new ArrayList<>(16);
                for (Object userIds : pageInfo.getList()) {
                    QueryWrapper<UserEntity> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.lambda().eq(UserEntity::getId, userIds);
                    entityList.add(this.getOne(queryWrapper1));
                }
                return entityList;
            } else {
                return new ArrayList<>();
            }
        }
        //关键字（账户、姓名、手机）
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            filterLastTime = true;
            queryWrapper.lambda().and(t -> t.like(UserEntity::getAccount, pagination.getKeyword()).or().like(UserEntity::getRealName, pagination.getKeyword()).or().like(UserEntity::getMobilePhone, pagination.getKeyword()));
        }
        //排序
        queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        if (filterLastTime) {
            queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
        }
        Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<UserEntity> iPage = this.page(page, queryWrapper);
        if (!iPage.getRecords().isEmpty()) {
            List<String> ids = iPage.getRecords().stream().map(m -> m.getId()).collect(Collectors.toList());
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, ids);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            if (filterLastTime) {
                queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
            }
            iPage.setRecords(this.list(queryWrapper));
        }
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<UserEntity> authorizeAddressGetList(PaginationUser pagination, String organizeId, Boolean flag) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean filterLastTime = false;
        String userId = userProvider.get().getUserId();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(UserEntity::getId);

        if (flag) {
            queryWrapper.lambda().ne(UserEntity::getId, userId);
        }
        //组织机构
        if (!StringUtils.isEmpty(organizeId)) {
            List<String> orgIdList = organizeService.getUnderOrganizations(organizeId);
            PageHelper.startPage((int) pagination.getCurrentPage(), (int) pagination.getPageSize());
            // 用户id
            List<String> query = null;
            String dbSchema = "";
            // 判断是否为多租户
            if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
                dbSchema = DataSourceContextHolder.getDatasourceName();
            } else {
                dbSchema = dataSourceModel.getDbSchema();
            }
            if ("kingbasees".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryKingbase(organizeId, orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else if ("oracle".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryOracle(organizeId, orgIdList, pagination.getKeyword(), null, null);
            } else if ("dm8".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryDm(organizeId, orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else {
                query = userMapper.query(organizeId, orgIdList, pagination.getKeyword(), null, null);
            }
            PageInfo pageInfo = new PageInfo(query);
            // 赋值分页参数
            pagination.setTotal(pageInfo.getTotal());
            pagination.setCurrentPage(pageInfo.getPageNum());
            pagination.setPageSize(pageInfo.getPageSize());
            if (pageInfo.getList().size() > 0) {
                // 存放返回结果
                List<UserEntity> entityList = new ArrayList<>(16);
                for (Object userIds : pageInfo.getList()) {
                    QueryWrapper<UserEntity> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.lambda().eq(UserEntity::getId, userIds);
                    entityList.add(this.getOne(queryWrapper1));
                }
                return entityList;
            } else {
                return new ArrayList<>();
            }
        }
        //关键字（账户、姓名、手机）
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            filterLastTime = true;
            queryWrapper.lambda().and(t -> t.like(UserEntity::getAccount, pagination.getKeyword()).or().like(UserEntity::getRealName, pagination.getKeyword()).or().like(UserEntity::getMobilePhone, pagination.getKeyword()));
        }
        if (StringUtils.isNotEmpty(pagination.getAlreadyAuthorize())) {
            List<UserRelationEntity> area = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area"));
            if (ObjectUtil.isNull(area)) {
                return new ArrayList<>();
            }
            List<String> collect = area.stream().map(UserRelationEntity::getUserId).distinct().collect(Collectors.toList());
            queryWrapper.lambda().in(UserEntity::getId, collect).eq(UserEntity::getEnabledMark, "1");

        }

        if (StringUtils.isNotEmpty(pagination.getAlreadyAuthorize()) && StringUtils.isNotEmpty(pagination.getOrganizeFlag())) {
            //根据组织id查询本公司的编码
            OrganizeEntity one = organizeService.getOne(Wrappers.<OrganizeEntity>lambdaQuery().eq(OrganizeEntity::getId, pagination.getOrganizeFlag()));
            List<UserEntity> allUserList = this.list(Wrappers.<UserEntity>lambdaQuery().like(UserEntity::getCode, one.getEnCode()));
            List<UserRelationEntity> areaUserList = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area"));
            List<String> allUserListIds = allUserList.stream().map(UserEntity::getId).collect(Collectors.toList());
            List<String> areaUserListIds = areaUserList.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
            //求两个集合的合集
            List<String> userListIds = allUserListIds.stream().filter(areaUserListIds::contains).collect(Collectors.toList());
            queryWrapper.lambda().in(UserEntity::getId, userListIds);
        }
        if (StringUtils.isNotEmpty(pagination.getAddress())) {
            if (pagination.getAddress().size() < 2 && pagination.getAddress().get(0).equals("10")) {
                pagination.setAddress(null);
            }
        }
        if (!StringUtils.isEmpty(pagination.getAddress())) {
            QueryWrapper<UserRelationEntity> userRelationEntityQueryWrapper = new QueryWrapper<>();
            List<String> addressList = JsonUtil.getJsonToList(pagination.getAddress(), String.class);
            if (addressList.size() > 1) {
                String collect = addressList.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
                collect = "[" + collect;
                //StringBuilder stringBuilder=new StringBuilder(addressList.get(0))
                String s = addressList.get(0);
                s = "[" + "\"" + s + "\"" + "]";
                userRelationEntityQueryWrapper.lambda().like(UserRelationEntity::getObjectId, collect).or().eq(UserRelationEntity::getObjectId, s);
            } else {
                String s = addressList.get(addressList.size() - 1);
                s = "[" + "\"" + s;
                userRelationEntityQueryWrapper.lambda().likeRight(UserRelationEntity::getObjectType, "Area").like(UserRelationEntity::getObjectId, s);
            }
            List<UserRelationEntity> list = userRelationService.list(userRelationEntityQueryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                List<String> collect = list.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                queryWrapper.lambda().in(UserEntity::getId, collect);
            } else {
                return new ArrayList<>();
            }

        }
        //排序
        queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        if (filterLastTime) {
            queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
        }
        Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<UserEntity> iPage = this.page(page, queryWrapper);
        if (!iPage.getRecords().isEmpty()) {
            List<String> ids = iPage.getRecords().stream().map(m -> m.getId()).collect(Collectors.toList());
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, ids);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            if (filterLastTime) {
                queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
            }
            iPage.setRecords(this.list(queryWrapper));
        }
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<UserEntity> getList(String keyword) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ne(UserEntity::getEnabledMark, 0);
        if (StringUtils.isNotEmpty(keyword)) {
            //通过关键字查询
            queryWrapper.lambda().and(t -> t.like(UserEntity::getAccount, keyword).or().like(UserEntity::getRealName, keyword).or().like(UserEntity::getMobilePhone, keyword));
        }
        queryWrapper.lambda().select(UserEntity::getId, UserEntity::getAccount, UserEntity::getRealName);
        Page<UserEntity> page = new Page<>(1, 50);
        IPage<UserEntity> iPage = this.page(page, queryWrapper);
        return iPage.getRecords();
    }

    @Override
    public List<UserEntity> getListByOrganizeId(String organizeId, String keyword) {
        List<String> userIds = userRelationService.getListByObjectId(organizeId, PermissionConst.ORGANIZE).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        if (userIds.size() > 0) {
            QueryWrapper<UserEntity> query = new QueryWrapper<>();
            if (userIds.size() > 0) {
                query.lambda().in(UserEntity::getId, userIds);
            }
            // 通过关键字查询
            if (StringUtils.isNotEmpty(keyword)) {
                query.lambda().and(t -> t.like(UserEntity::getAccount, keyword).or().like(UserEntity::getRealName, keyword));
            }
            // 只查询正常的用户
            query.lambda().eq(UserEntity::getEnabledMark, 1);
            query.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            return this.list(query);
        }
        return new ArrayList<>(0);
    }

    @Override
    public List<UserEntity> getListByManagerId(String managerId, String keyword) {

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getManagerId, managerId);

        //获取管理的部门
        List<OrganizeEntity> listAscByManagerId = organizeService.getListAscByManagerId(managerId);
        List<String> orgIds = listAscByManagerId.stream().map(OrganizeEntity::getId).collect(Collectors.toList());
        List<String> userIds = new ArrayList<>();
        if (null != orgIds && orgIds.size() > 0) {
            //获取部门下的用户
            List<UserRelationEntity> listByOrgId = userRelationService.getListByOrgId(orgIds);
            userIds = listByOrgId.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
            if (null != userIds && userIds.size() > 0) {
                queryWrapper.lambda().or().in(UserEntity::getId, userIds);
            }
        }
        // 通过关键字查询
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(t -> t.like(UserEntity::getAccount, keyword).or().like(UserEntity::getRealName, keyword));
        }
        // 只查询正常的用户
        queryWrapper.lambda().eq(UserEntity::getEnabledMark, 1);
        queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public UserEntity getInfo(String id) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<UserEntity> getInfoByCode(String code) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getCode, code);
        return this.list(queryWrapper);
    }
    @Override
    public UserEntity getUserByAccount(String account) throws LoginException {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getAccount, account)
                .or().eq(UserEntity::getEmail, account)
                .or().eq(UserEntity::getMobilePhone, account);
        List<UserEntity> userEntityList = this.list(queryWrapper);
        //用户数据重复
        if (CollectionUtil.isNotEmpty(userEntityList)&&userEntityList.size()>1) {
            String errorMessage = String.format(MsgCode.LOG014.get());
            throw new LoginException(errorMessage);
        }
        UserEntity userEntity = userEntityList.stream().findFirst().orElse(null);
        return userEntity;
    }

    @Override
    public UserEntity getUserEntity(String account, String phone, String email) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getAccount, account)
                .or().eq(UserEntity::getEmail, phone)
                .or().eq(UserEntity::getMobilePhone, email);
        List<UserEntity> userEntityList = this.list(queryWrapper);
        UserEntity userEntity = userEntityList.stream().findFirst().orElse(null);
        return userEntity;
    }

    @Override
    public Boolean setAdminListByIds(List<String> adminIds) {
        // 将所有的管理员取消
        QueryWrapper<UserEntity> query = new QueryWrapper<>();
        query.lambda().eq(UserEntity::getIsAdministrator, 1);
        // admin不允许移除管理员
        query.lambda().ne(UserEntity::getId, "admin");
        List<UserEntity> list1 = this.list(query);
        for (UserEntity entity : list1) {
            entity.setIsAdministrator(0);
            this.updateById(entity);
        }
        // 重新赋值管理员
        List<UserEntity> list = new ArrayList<>();
        // admin无需添加
        adminIds.remove("admin");
        adminIds.stream().forEach(adminId -> {
            UserEntity userEntity = new UserEntity();
            userEntity.setId(adminId);
            userEntity.setIsAdministrator(1);
            list.add(userEntity);
        });
        return this.updateBatchById(list);
    }

    @Override
    public boolean isExistByAccount(String account) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserEntity::getAccount, account)
                .or().eq(UserEntity::getEmail, account)
                .or().eq(UserEntity::getMobilePhone, account);
        UserEntity entity = this.getOne(queryWrapper);
        if (entity != null) {
            return true;
        }
        return false;
    }

    @Override
    @DSTransactional
    public Boolean create(UserEntity entity) throws Exception {
        //获取头像
        String oldHeadIcon = entity.getHeadIcon();
        if (StringUtils.isEmpty(oldHeadIcon)) {
            entity.setHeadIcon("/api/file/Image/userAvatar/001.png");
        }
        if (this.isExistByAccount(entity.getAccount())) {
            throw new PermissionException("账户名称不能重复");
        }
        //添加用户 初始化
        String userId = "";
        if (ObjectUtil.isEmpty(entity.getId())) {
            userId = RandomUtil.uuId();
            entity.setId(userId);
        } else {
            userId = entity.getId();
        }

        entity.setSecretkey(RandomUtil.uuId());
        entity.setPassword(this.getDefaultPassword(entity.getSecretkey()));
        entity.setIsAdministrator(0);
        entity.setCreatorUserId(userProvider.get().getUserId());
        saveOrUpdateCommon(userId, entity);
        this.save(entity);
        UserInfo operatorUser = userProvider.get();
        threadPoolExecutor.execute(() -> {
            try {
                //添加用户之后判断是否需要同步到企业微信
                synPushToThirdQyService.createUserSysToQy(operatorUser, false, entity, null);
                //添加用户之后判断是否需要同步到钉钉
//                synThirdDingTalkService.createUserSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("添加用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        String catchKey = cacheKeyUtil.getAllUser();
        if (redisUtil.exists(catchKey)) {
            redisUtil.remove(catchKey);
        }
        return true;
    }

    @Override
    @DSTransactional
    public Boolean createUser(UserEntity entity) throws Exception {
        //添加用户 初始化
        entity.setSecretkey(RandomUtil.uuId());
        entity.setId(RandomUtil.uuId());
        // 新增
        entity.setPassword(this.getDefaultPassword(entity.getSecretkey()));
        entity.setIsAdministrator(0);
        entity.setCreatorUserId(userProvider.get().getUserId());
        saveOrUpdateCommon(entity.getId(), entity);
        this.save(entity);
        return true;
    }


    @Override
    @DSTransactional
    public Boolean update(String userId, UserEntity entity) throws Exception {
        //将禁用的id加进数据
        UserEntity originUser = this.getInfo(userId);
        UserInfo operatorUser = userProvider.get();

        if ("1".equals(String.valueOf(originUser.getIsAdministrator()))) {

            // 管理员可以修改自己，但是无法修改其他管理员
            if (operatorUser.getIsAdministrator()) {
                if (!"admin".equals(operatorUser.getUserId())) {
                    if (!operatorUser.getUserId().equals(userId)) {
                        throw new PermissionException("管理员只能修改自己，不能修改其他管理员");
                    }
                }
            } else {
                throw new PermissionException("无法修改管理员账户");
            }
        }
        //直属主管不能是自己
        if (userId.equals(entity.getManagerId())) {
            throw new PermissionException("直属主管不能是自己");
        }
        if (!originUser.getAccount().equals(entity.getAccount())) {
            if (this.isExistByAccount(entity.getAccount())) {
                throw new PermissionException("账户名称不能重复");
            }
        }
        // 验证是否有十级,验证是否是自己的下属
        boolean subordinate = this.isSubordinate(userId, entity.getManagerId());
        if (subordinate) {
            throw new PermissionException("直属主管不能是我的下属用户");
        }
        // 如果账号被锁定
        if ("2".equals(String.valueOf(entity.getEnabledMark()))) {
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
        }
        // 如果原来是锁定，现在不锁定，则置空错误次数
        if (originUser.getEnabledMark() == 2 && entity.getEnabledMark() == 1) {
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
        }
        //更新用户
        entity.setId(userId);
        entity.setLastModifyTime(DateUtil.getNowDate());
        entity.setLastModifyUserId(userProvider.get().getUserId());
        //获取头像
//        String[] headIcon = entity.getHeadIcon().split("/");
//        if (headIcon.length > 0) {
//            entity.setHeadIcon(headIcon[headIcon.length - 1]);
//        }
        saveOrUpdateCommon(userId, entity);
        this.updateById(entity);


        //修改授权时给userRelation添加数据，先删除-再添加
        List<UserRelationEntity> area = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, originUser.getId()));
        List<String> ids = area.stream().map(UserRelationEntity::getId).collect(Collectors.toList());
        userRelationService.delete(ids.toArray(new String[]{}));
        if (ObjectUtil.isNotEmpty(entity.getAuthorizeAddress())) {
            UserRelationEntity userRelationEntity = new UserRelationEntity();

            userRelationEntity.setUserId(originUser.getId());
            userRelationEntity.setObjectType("Area");
            userRelationEntity.setCreatorUserId(operatorUser.getUserId());
            userRelationEntity.setCreatorTime(DateUtil.getNowDate());
            for (String authorizeAddress : entity.getAuthorizeAddress()) {

                String mainId = RandomUtil.uuId();
                userRelationEntity.setId(mainId);
                String collect = "";
                String[] split = authorizeAddress.replace("[\"", "").replace("\"]", "").replaceAll("\"", "").split(",");
                List<String> list1 = new ArrayList<>();
                for (String s : split) {
                    list1.add(s);
                }
                collect = list1.stream().map((s) -> "\"" + s + "\"").collect(Collectors.joining(","));
                collect = "[" + collect + "]";
                userRelationEntity.setObjectId(collect);
                userRelationService.save(userRelationEntity);
            }
        }

        threadPoolExecutor.execute(() -> {
            try {
                //修改用户之后判断是否需要同步到企业微信
                synPushToThirdQyService.updateUserSysToQy(operatorUser, false, entity, null);
                //修改用户之后判断是否需要同步到钉钉
//                synThirdDingTalkService.updateUserSysToDing(false, entity, "");
            } catch (Exception e) {
                log.error("修改用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
            }
        });
        // 删除在线的用户
        this.delCurUser(Collections.singletonList(userId));
        return true;
    }

    @Override
    public Boolean saveOrUpdateCommon(String userId, UserEntity entity) {
        List<String> userAllOrgIds = Arrays.asList(entity.getOrganizeId().split(","));
        List<String> userAllPosIds = StringUtils.isNotEmpty(entity.getPositionId()) ? Arrays.asList(entity.getPositionId().split(",")) : new ArrayList<>();
        List<String> userAllRoleIds = StringUtils.isNotEmpty(entity.getRoleId()) ? Arrays.asList(entity.getRoleId().split(",")) : new ArrayList<>();

        // 更新用户关系（组织/岗位/角色）
        List<UserRelationEntity> relationList = new ArrayList<>();
        setUserRelation(relationList, PermissionConst.ORGANIZE, userAllOrgIds, entity);
        setUserRelation(relationList, PermissionConst.POSITION, userAllPosIds, entity);
        setUserRelation(relationList, PermissionConst.ROLE, userAllRoleIds, entity);
        if (userId != null) {
            // 删除用户关联
            userRelationService.deleteAllByUserId(userId);
        }
        if (relationList.size() > 0) {
            userRelationService.saveBatch(relationList);
        }

        /*========== 自动设置带有权限的默认组织、自动设置默认岗位 ==========*/
        String majorOrgId = "";
        String majorPosId = "";
        UserEntity userEntity = this.getInfo(userId);
        if (userEntity != null) {
            // 原本的主岗、主组织
            majorOrgId = userEntity.getOrganizeId();
            majorPosId = userEntity.getPositionId();
        }
        majorOrgId = organizeRelationService.autoGetMajorOrganizeId(userId, userAllOrgIds, majorOrgId);
        entity.setOrganizeId(majorOrgId);
        if (userAllPosIds.size() > 0) {
            entity.setPositionId(organizeRelationService.autoGetMajorPositionId(userId, majorOrgId, majorPosId));
        } else {
            entity.setPositionId("");
        }
        entity.setQuickQuery(PinYinUtil.getFirstSpell(entity.getRealName()));
        //清理获取所有用户的redis缓存
        redisUtil.remove(cacheKeyUtil.getAllUser());
        return true;
    }

    /**
     * 设置用户关联对象
     */
    private void setUserRelation(List<UserRelationEntity> relationList, String objectType, List<String> ids, UserEntity userEntity) {
        for (String id : ids) {
            UserRelationEntity relationEntity = new UserRelationEntity();
            relationEntity.setId(RandomUtil.uuId());
            relationEntity.setObjectType(objectType);
            relationEntity.setObjectId(id);
            relationEntity.setUserId(userEntity.getId());
            relationEntity.setCreatorTime(userEntity.getCreatorTime());
            relationEntity.setCreatorUserId(userEntity.getCreatorUserId());
            relationList.add(relationEntity);
        }
    }

    /**
     * 批量设置部门下的所有用户主管
     *
     * @param organizeId 主键值
     */
    @Override
    @DSTransactional
    public Boolean updateMangerIdByOrganizeId(String organizeId, String managerId) {
        List<String> userIds = userRelationService.getListByObjectId(organizeId, PermissionConst.ORGANIZE).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        if (userIds.size() > 0) {
            QueryWrapper<UserEntity> query = new QueryWrapper<>();
            if (userIds.size() > 0) {
                query.lambda().in(UserEntity::getId, userIds);
            }
            query.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            List<UserEntity> userList = this.list(query);
            for (UserEntity userEntity : userList) {
                userEntity.setManagerId(managerId);
            }
            this.updateBatchById(userList);
        }
        return true;
    }

    @Override
    @DSTransactional
    public void delete(UserEntity entity) throws Exception {
        this.delete(entity, null);
    }
    @Override
    @DSTransactional
    public void delete(UserEntity entity, String actionType) throws Exception {
        if ("1".equals(String.valueOf(entity.getIsAdministrator()))) {
            throw new PermissionException("无法删除管理员账户");
        }
        //判断是否是部门主管
        if (organizeService.getList().stream().filter(t -> entity.getId().equals(t.getManagerId())).collect(Collectors.toList()).size() > 0) {
            throw new PermissionException("此用户为某部门主管，无法删除");
        }
        // 有下属不允许删除
        if (this.getListByManagerId(entity.getId(), null).size() > 0) {
            throw new PermissionException("此用户有下属，无法删除");
        }
        String tenantId = StringUtils.isEmpty(userProvider.get().getTenantId()) ? "" : userProvider.get().getTenantId();
        String catchKey = tenantId + "allUser";
        if (redisUtil.exists(catchKey)) {
            redisUtil.remove(catchKey);
        }

        this.removeById(entity.getId());
        //删除用户关联
        QueryWrapper<UserRelationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserRelationEntity::getUserId, entity.getId());
        userRelationService.remove(queryWrapper);

        if (StringUtils.isEmpty(actionType) || actionType.equals(SYS_DELETE)) {
            // 操作类型为空或系统删除，执行第三方同步。
            UserInfo operatorUser = userProvider.get();
            threadPoolExecutor.execute(() -> {
                try {
                    //删除用户之后判断是否需要同步到企业微信
                    synPushToThirdQyService.deleteUserSysToQy(operatorUser, false, entity.getId(), null);
                    //删除用户之后判断是否需要同步到钉钉
//                synThirdDingTalkService.deleteUserSysToDing(false, entity.getId(), "");
                } catch (Exception e) {
                    log.error("删除用户之后同步失败到企业微信或钉钉失败，异常：" + e.getMessage());
                }
            });
        }

        userProvider.removeOnLine(entity.getId());
        RemoveUtil.removeOnline(entity.getId());
    }


    @Override
    public void updatePassword(UserEntity entity) {
        entity.setSecretkey(RandomUtil.uuId());
        entity.setPassword(Md5Util.getStringMd5(entity.getPassword().toLowerCase() + entity.getSecretkey().toLowerCase()));
        entity.setChangePasswordDate(DateUtil.getNowDate());
        this.updateById(entity);
    }

    @Override
    public List<UserEntity> getUserName(List<String> id) {
        List<UserEntity> list = new ArrayList<>();
        // 达梦数据库无法null值入参
        id.removeAll(Collections.singleton(null));
        if (id.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, id);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<UserEntity> getUserList(List<String> id) {
        List<UserEntity> list = new ArrayList<>();
        // 达梦数据库无法null值入参
        id.removeAll(Collections.singleton(null));
        if (id.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, id);
            queryWrapper.lambda().ne(UserEntity::getEnabledMark, 0);
            queryWrapper.lambda().select(UserEntity::getId);
            list = this.list(queryWrapper);
        }
        return list;
    }

    @Override
    public List<String> getListId() {
        return this.baseMapper.getListId();
    }

    @Override
    public void update(UserEntity entity, String type) {
        UpdateWrapper<UserEntity> wrapper = new UpdateWrapper<>();
        if ("Position".equals(type)) {
            wrapper.lambda().set(UserEntity::getPositionId, entity.getPositionId());
        } else {
            wrapper.lambda().set(UserEntity::getRoleId, entity.getRoleId());
        }
        wrapper.lambda().eq(UserEntity::getId, entity.getId());
        this.update(wrapper);
    }

    @Override
    public boolean isSubordinate(String id, String managerId) {
        int num = 0;
        return recursionSubordinates(id, managerId, num);
    }

    @Override
    public DownloadVO exportExcel(String dataType, String selectKey, PaginationUser pagination) {
        List<UserEntity> entityList = new ArrayList<>();
        if ("0".equals(dataType)) {
            entityList = getList(pagination, pagination.getOrganizeId(), false);
        } else if ("1".equals(dataType)) {
            entityList = getList();
        }
        List<UserExportVO> modeList = new ArrayList<>();
        List<OrganizeEntity> organizeList = null;
        // 长度超过300代表是全部数据
        if (entityList.size() > 300) {
            // 大约100则直接初始化给100
            organizeList = new ArrayList<>(100);
            List<String> organizeId = entityList.stream().map(t -> t.getOrganizeId()).collect(Collectors.toList());
            organizeList = organizeService.getOrganizeName(organizeId);
        }
        for (UserEntity entity : entityList) {
            UserExportVO model = new UserExportVO();
            model.setAccount(entity.getAccount());
            model.setRealName(entity.getRealName());
            // 组织
            // 定义多组织集合
            StringBuffer stringBuffer = new StringBuffer();
            // 获取该用户的所有组织关系
            List<UserRelationEntity> allOrgRelationByUserId = userRelationService.getAllOrgRelationByUserId(entity.getId());
            for (UserRelationEntity userRelationEntity : allOrgRelationByUserId) {
                String id = userRelationEntity.getObjectId();
                OrganizeEntity organize = null;
                // 得到该组织信息
                if (organizeList != null) {
                    organize = organizeList.stream().filter(t -> id.equals(t.getId())).findFirst().orElse(null);
                } else {
                    organize = organizeService.getInfo(id);
                }
                // 得到父级id树
                if (organize != null && StringUtils.isNotEmpty(organize.getOrganizeIdTree())) {
                    String[] split = organize.getOrganizeIdTree().split(",");
                    StringBuffer organizeIdTree = new StringBuffer();
                    for (String parentId : split) {
                        OrganizeEntity organizes = null;
                        if (organizeList != null) {
                            organizes = organizeList.stream().filter(t -> parentId.equals(t.getId())).findFirst().orElse(null);
                        } else {
                            organizes = organizeService.getInfo(parentId);
                        }
                        if (Objects.nonNull(organizes) && StringUtils.isNotEmpty(organizes.getFullName())) {
                            organizeIdTree.append("/" + organizes.getFullName());
                        }
                    }
                    String toString = organizeIdTree.toString();
                    if (StringUtils.isNotEmpty(toString)) {
                        String organizeId = toString.replaceFirst("/", "");
                        stringBuffer.append("," + organizeId);
                    }
                }
            }
            model.setOrganizeId(stringBuffer.toString().replaceFirst(",", ""));
            // 主管
            UserEntity info = getInfo(entity.getManagerId());
            if (Objects.nonNull(info) && StringUtils.isNotEmpty(info.getRealName()) && StringUtils.isNotEmpty(info.getAccount())) {
                model.setManagerId(info.getRealName());
            }
            // 岗位
            List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(entity.getId(), PermissionConst.POSITION);
            StringBuffer positionName = new StringBuffer();
            for (UserRelationEntity userRelationEntity : listByObjectType) {
                if (StringUtils.isNotEmpty(userRelationEntity.getObjectId())) {
                    PositionEntity positionEntity = positionService.getInfo(userRelationEntity.getObjectId());
                    if (Objects.nonNull(positionEntity)) {
                        positionName.append("," + positionEntity.getFullName() + "/" + positionEntity.getEnCode());
                    }
                }
            }
            // 判断岗位是否需要导出
            if (positionName.length() > 0) {
                model.setPositionId(positionName.toString().replaceFirst(",", ""));
            }

            // 角色
            List<UserRelationEntity> listByObjectType1 = userRelationService.getListByObjectType(entity.getId(), PermissionConst.ROLE);
            StringBuffer roleName = new StringBuffer();
            for (UserRelationEntity userRelationEntity : listByObjectType1) {
                if (StringUtils.isNotEmpty(userRelationEntity.getObjectId())) {
                    RoleEntity roleEntity = roleService.getInfo(userRelationEntity.getObjectId());
                    if (Objects.nonNull(roleEntity)) {
                        roleName.append("," + roleEntity.getFullName());
                    }
                }
            }
            if (roleName.length() > 0) {
                model.setRoleId(roleName.toString().replaceFirst(",", ""));
            }

            model.setDescription(entity.getDescription());
            // 性别
            if (entity.getGender() != null) {
                if (entity.getGender() == 1) {
                    model.setGender("男");
                } else if (entity.getGender() == 2) {
                    model.setGender("女");
                } else if (entity.getGender() == 3) {
                    model.setGender("保密");
                }
            }
            // 性别
            DictionaryDataEntity dictionaryDataEntity = dictionaryDataService.getInfo(entity.getNation());
            if (Objects.nonNull(dictionaryDataEntity)) {
                model.setNation(dictionaryDataEntity.getFullName());
            }
            model.setNativePlace(entity.getNativePlace());
            // 证件类型
            DictionaryDataEntity dictionaryDataEntity1 = dictionaryDataService.getInfo(entity.getCertificatesType());
            if (Objects.nonNull(dictionaryDataEntity1)) {
                model.setCertificatesType(dictionaryDataEntity1.getFullName());
            }
            model.setCertificatesNumber(entity.getCertificatesNumber());
            // 文化程度
            DictionaryDataEntity dictionaryDataEntity2 = dictionaryDataService.getInfo(entity.getEducation());
            if (Objects.nonNull(dictionaryDataEntity2)) {
                model.setEducation(dictionaryDataEntity2.getFullName());
            }
            // 生日
            SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd");
            if (entity.getBirthday() != null) {
                String birthday = sf1.format(entity.getBirthday());
                model.setBirthday(birthday);
            }
            model.setTelePhone(entity.getTelePhone());
            model.setLandline(entity.getLandline());
            model.setMobilePhone(entity.getMobilePhone());
            model.setEmail(entity.getEmail());
            model.setUrgentContacts(entity.getUrgentContacts());
            model.setUrgentTelePhone(entity.getUrgentTelePhone());
            model.setPostalAddress(entity.getPostalAddress());
            model.setSortCode(entity.getSortCode());
            // 设置状态
            if (entity.getEnabledMark() == 0) {
                model.setEnabledMark("禁用");
            } else if (entity.getEnabledMark() == 1) {
                model.setEnabledMark("正常");
            } else {
                model.setEnabledMark("锁定");
            }
            // 入职时间
            if (entity.getEntryDate() != null) {
                String entryDate = sf1.format(entity.getEntryDate());
                model.setEntryDate(entryDate);
            }
            modeList.add(model);
        }
        return exportUtil(selectKey, "用户信息", modeList);
    }

    private DownloadVO exportUtil(String selectKey, String explain, List<UserExportVO> modeList) {
        List<UserExportVO> list = JsonUtil.listToJsonField(JsonUtil.getJsonToList(modeList, UserExportVO.class));
        List<ExcelExportEntity> entitys = new ArrayList<>();
        String[] splitData = selectKey.split(",");
        if (splitData.length > 0) {
            for (int i = 0; i < splitData.length; i++) {
                if (splitData[i].equals("account")) {
                    entitys.add(new ExcelExportEntity("账号", "account"));
                }
                if (splitData[i].equals("realName")) {
                    entitys.add(new ExcelExportEntity("姓名", "realName"));
                }
                if (splitData[i].equals("organizeId")) {
                    entitys.add(new ExcelExportEntity("所属组织", "organizeId"));
                }
                if (splitData[i].equals("managerId")) {
                    entitys.add(new ExcelExportEntity("直属主管", "managerId"));
                }
                if (splitData[i].equals("positionId")) {
                    entitys.add(new ExcelExportEntity("岗位", "positionId"));
                }
                if (splitData[i].equals("roleId")) {
                    entitys.add(new ExcelExportEntity("角色", "roleId"));
                }
                if (splitData[i].equals("description")) {
                    entitys.add(new ExcelExportEntity("说明", "description", 25));
                }
                if (splitData[i].equals("gender")) {
                    entitys.add(new ExcelExportEntity("性别", "gender"));
                }
                if (splitData[i].equals("nation")) {
                    entitys.add(new ExcelExportEntity("民族", "nation"));
                }
                if (splitData[i].equals("nativePlace")) {
                    entitys.add(new ExcelExportEntity("籍贯", "nativePlace"));
                }
                if (splitData[i].equals("certificatesType")) {
                    entitys.add(new ExcelExportEntity("证件类型", "certificatesType"));
                }
                if (splitData[i].equals("certificatesNumber")) {
                    entitys.add(new ExcelExportEntity("证件号码", "certificatesNumber"));
                }
                if (splitData[i].equals("education")) {
                    entitys.add(new ExcelExportEntity("文化程度", "education"));
                }
                if (splitData[i].equals("birthday")) {
                    entitys.add(new ExcelExportEntity("生日", "birthday"));
                }
                if (splitData[i].equals("telePhone")) {
                    entitys.add(new ExcelExportEntity("电话", "telePhone"));
                }
                if (splitData[i].equals("landline")) {
                    entitys.add(new ExcelExportEntity("固定电话", "landline"));
                }
                if (splitData[i].equals("mobilePhone")) {
                    entitys.add(new ExcelExportEntity("手机", "mobilePhone"));
                }
                if (splitData[i].equals("email")) {
                    entitys.add(new ExcelExportEntity("邮箱", "email"));
                }
                if (splitData[i].equals("urgentContacts")) {
                    entitys.add(new ExcelExportEntity("紧急联系人", "urgentContacts"));
                }
                if (splitData[i].equals("urgentTelePhone")) {
                    entitys.add(new ExcelExportEntity("紧急电话", "urgentTelePhone"));
                }
                if (splitData[i].equals("postalAddress")) {
                    entitys.add(new ExcelExportEntity("通讯地址", "postalAddress", 25));
                }
                if (splitData[i].equals("sortCode")) {
                    entitys.add(new ExcelExportEntity("排序码", "sortCode"));
                }
                if (splitData[i].equals("enabledMark")) {
                    entitys.add(new ExcelExportEntity("状态", "enabledMark"));
                }
                if (splitData[i].equals("entryDate")) {
                    entitys.add(new ExcelExportEntity("入职日期", "entryDate"));
                }
            }
        }
        ExportParams exportParams = new ExportParams(null, "用户信息");
        exportParams.setType(ExcelType.XSSF);

        DownloadVO vo = DownloadVO.builder().build();
        try {
            @Cleanup Workbook workbook = new HSSFWorkbook();
            if (entitys.size() > 0) {
                workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
            }
            String name = explain + DateUtil.dateNow("yyyyMMdd") + "_" + RandomUtil.uuId() + ".xlsx";
            String fileName = configValueUtil.getTemporaryFilePath() + name;
            @Cleanup FileOutputStream output = new FileOutputStream(fileName);
            workbook.write(output);
            //上传文件
            UploadUtil.uploadFile(configValueUtil.getFileType(), fileName, FileTypeEnum.TEMPORARY, name);
            vo.setName(name);
            vo.setUrl(UploaderUtil.uploaderFile(userProvider.get().getId() + "#" + name + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("用户信息导出Excel错误:" + e.getMessage());
        }
        return vo;
    }

    @Override
    public Map<String, Object> importPreview(List<UserExportVO> personList) {
        List<Map<String, Object>> dataRow = new ArrayList<>();
        List<Map<String, Object>> columns = new ArrayList<>();
        for (int i = 0; i < personList.size(); i++) {
            Map<String, Object> dataRowMap = new HashMap<>();
            UserExportVO model = personList.get(i);
            dataRowMap.put("account", model.getAccount());
            dataRowMap.put("realName", model.getRealName());
            dataRowMap.put("organizeId", model.getOrganizeId());
            dataRowMap.put("managerId", model.getManagerId());
            dataRowMap.put("positionId", model.getPositionId());
            dataRowMap.put("roleId", model.getRoleId());
            dataRowMap.put("description", model.getDescription());
            dataRowMap.put("gender", model.getGender());
            dataRowMap.put("nation", model.getNation());
            dataRowMap.put("nativePlace", model.getNativePlace());
            dataRowMap.put("certificatesType", model.getCertificatesType());
            dataRowMap.put("certificatesNumber", model.getCertificatesNumber());
            dataRowMap.put("education", model.getEducation());
            dataRowMap.put("birthday", model.getBirthday());
            dataRowMap.put("telePhone", model.getTelePhone());
            dataRowMap.put("landline", model.getLandline());
            dataRowMap.put("mobilePhone", model.getMobilePhone());
            dataRowMap.put("email", model.getEmail());
            dataRowMap.put("urgentContacts", model.getUrgentContacts());
            dataRowMap.put("urgentTelePhone", model.getUrgentTelePhone());
            dataRowMap.put("postalAddress", model.getPostalAddress());
            dataRowMap.put("sortCode", model.getSortCode());
            dataRowMap.put("enabledMark", model.getEnabledMark());
            dataRowMap.put("entryDate", model.getEntryDate());
            dataRow.add(dataRowMap);
        }
        for (int i = 1; i <= personList.size(); i++) {
            Map<String, Object> columnsMap = new HashMap<>();
            columnsMap.put("AllowDBNull", true);
            columnsMap.put("AutoIncrement", false);
            columnsMap.put("AutoIncrementSeed", 0);
            columnsMap.put("AutoIncrementStep", 1);
            columnsMap.put("Caption", this.getColumns(i));
            columnsMap.put("ColumnMapping", 1);
            columnsMap.put("ColumnName", this.getColumns(i));
            columnsMap.put("Container", null);
            columnsMap.put("DataType", "System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            columnsMap.put("DateTimeMode", 3);
            columnsMap.put("DefaultValue", null);
            columnsMap.put("DesignMode", false);
            columnsMap.put("Expression", "");
            columnsMap.put("ExtendedProperties", "");
            columnsMap.put("MaxLength", -1);
            columnsMap.put("Namespace", "");
            columnsMap.put("Ordinal", 0);
            columnsMap.put("Prefix", "");
            columnsMap.put("ReadOnly", false);
            columnsMap.put("Site", null);
            columnsMap.put("Table", personList);
            columnsMap.put("Unique", false);
            columns.add(columnsMap);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("dataRow", dataRow);
        map.put("columns", columns);
        return map;
    }

    @Override
    public UserImportVO importData(List<UserExportVO> dataList) throws PermissionException {
        List<UserImportModel> importModels = new ArrayList<>(16);
        List<UserExportVO> exceptionList = new ArrayList<>(16);
        // 得到民族集合
        List<DictionaryDataEntity> dataServiceList = dictionaryDataService.getList("b6cd65a763fa45eb9fe98e5057693e40");
        // 得到证件类型
        List<DictionaryDataEntity> dataServiceList1 = dictionaryDataService.getList("7866376d5f694d4d851c7164bd00ebfc");
        // 得到文化程度
        List<DictionaryDataEntity> dataServiceList2 = dictionaryDataService.getList("6a6d6fb541b742fbae7e8888528baa16");
        // 去除重复的account
        Map<String, Long> collect = dataList.stream().filter(t -> StringUtils.isNotBlank(t.getAccount())).collect(Collectors.groupingBy(t -> t.getAccount(), Collectors.counting()));
        List<String> collect1 = collect.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()).collect(Collectors.toList());
        for (String account : collect1) {
            List<UserExportVO> collect2 = dataList.stream().filter(t -> account.equals(t.getAccount())).collect(Collectors.toList());
            dataList.removeAll(collect2);
            exceptionList.addAll(collect2);
        }

        for (UserExportVO exportVO : dataList) {
            UserImportModel model = new UserImportModel();
            // 处理账号
            if (StringUtils.isNotEmpty(exportVO.getAccount())) {
                UserEntity userByAccount = getUserByAccount(exportVO.getAccount());
                if (Objects.nonNull(userByAccount)) {
                    // 账号重复
                    exceptionList.add(exportVO);
                    continue;
                }
                String regex = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";
                if (!exportVO.getAccount().matches(regex)) {
                    // 账号重复
                    exceptionList.add(exportVO);
                    continue;
                }
                model.setAccount(exportVO.getAccount());
            } else {
                // 账号为空
                exceptionList.add(exportVO);
                continue;
            }
            // 处理姓名
            if (StringUtils.isEmpty(exportVO.getRealName())) {
                // 姓名为空
                exceptionList.add(exportVO);
                continue;
            }
            model.setRealName(exportVO.getRealName());
            // 处理组织id
            String organizeId = exportVO.getOrganizeId();
            if (StringUtils.isEmpty(organizeId)) {
                // 判断如果所属组织为空，则为错误数据
                exceptionList.add(exportVO);
                continue;
            }
            // 处理多级组织
            String[] organizeIds = organizeId.split(",");
            // 储存字段
            StringBuffer stringBuffer = new StringBuffer();
            // 处理单个组织
            for (String id : organizeIds) {
                String[] split = id.split("/");
                // 定义一个标志，当前部门如果不存在则存到错误集合中
                boolean isOk = false;
                if (split.length > 0) {
                    // 从父级一级一级取
                    OrganizeEntity organizeEntity = null;
                    List<OrganizeEntity> infoByFullName = organizeService.getListByFullName(split[0]);
                    for (OrganizeEntity entity : infoByFullName) {
                        if ("-1".equals(entity.getParentId())) {
                            organizeEntity = entity;
                            break;
                        }
                    }
                    // 从第2个开始遍历
                    if (split.length > 1) {
                        for (int i = 1; i < split.length; i++) {
                            List<OrganizeEntity> infoByFullName1 = organizeService.getListByFullName(split[i]);
                            // 如果部门不存在则无法导入成功
                            if (infoByFullName1.size() < 1) {
                                isOk = true;
                                break;
                            }
                            for (OrganizeEntity entity : infoByFullName1) {
                                if (organizeEntity != null && organizeEntity.getId().equals(entity.getParentId())) {
                                    organizeEntity = entity;
                                    break;
                                }
                            }
                        }
                    }
                    if (!isOk && Objects.nonNull(organizeEntity)) {
                        if (model != null) {
                            stringBuffer.append("," + organizeEntity.getId());
                        }
                    }
                } else {
                    // 判断如果所属组织不存在，则为错误数据
                    exceptionList.add(exportVO);
                    continue;
                }
            }
            if (stringBuffer.length() < 1) {
                exceptionList.add(exportVO);
                continue;
            }
            model.setOrganizeId(stringBuffer.toString().replaceFirst(",", ""));
            // 处理主管id
            String managerId = exportVO.getManagerId();
            if (StringUtils.isNotEmpty(managerId)) {
                String[] split1 = managerId.split("/");
                if (split1.length > 0) {
                    String account = split1[split1.length - 1];
                    UserEntity entity = getUserByAccount(account);
                    if (Objects.nonNull(entity) && StringUtils.isNotEmpty(entity.getAccount())) {
                        model.setManagerId(entity.getId());
                    }
                }
            }
            // 处理岗位id
            String positionId = exportVO.getPositionId();
            if (StringUtils.isNotEmpty(positionId)) {
                StringBuffer positionIdBuffer = new StringBuffer();
                String[] positionIds = positionId.split(",");
                for (String id : positionIds) {
                    // 岗位名称+编码
                    String[] positionName = id.split("/");
                    // 无编码无名称代表是无用数据，不予保存
                    if (positionName != null && positionName.length > 1) {
                        // 通过名称和编码获取岗位信息
                        List<PositionEntity> positionEntityList = positionService.getListByFullName(positionName[0], positionName[1]);
                        if (positionEntityList != null && positionEntityList.size() > 0) {
                            PositionEntity positionEntity = positionEntityList.get(0);
                            positionIdBuffer.append("," + positionEntity.getId());
                        }
                    } else {
                        continue;
                    }
                }
                model.setPositionId(positionIdBuffer.toString().replaceFirst(",", ""));
            }
            // 处理角色id
            if (StringUtils.isNotEmpty(exportVO.getRoleId())) {
                String[] roleNames = exportVO.getRoleId().split(",");
                StringBuffer roleId = new StringBuffer();
                for (String roleName : roleNames) {
                    RoleEntity roleEntity = roleService.getInfoByFullName(roleName);
                    if (Objects.nonNull(roleEntity)) {
                        roleId.append("," + roleEntity.getId());
                    }
                }
                model.setRoleId(roleId.toString().replaceFirst(",", ""));
            }
            model.setDescription(exportVO.getDescription());
            // 处理性别
            if (StringUtils.isEmpty(exportVO.getGender())) {
                // 性别为必填项，不给默认为错误，不给默认值
                exceptionList.add(exportVO);
                continue;
            }
            if ("男".equals(exportVO.getGender())) {
                model.setGender(1);
            } else if ("女".equals(exportVO.getGender())) {
                model.setGender(2);
            } else {
                model.setGender(3);
            }
            // 处理民族
            if (StringUtils.isNotEmpty(exportVO.getNation())) {
                // 拿到民族的数据
                DictionaryDataEntity dataEntity = dataServiceList.stream().filter(t -> exportVO.getNation().equals(t.getFullName())).findFirst().orElse(null);
                model.setNation(dataEntity != null ? dataEntity.getFullName() : null);
            }
            model.setNativePlace(exportVO.getNativePlace());
            // 处理证件类型
            if (StringUtils.isNotEmpty(exportVO.getCertificatesType())) {
                DictionaryDataEntity dataEntity = dataServiceList1.stream().filter(t -> exportVO.getCertificatesType().equals(t.getFullName())).findFirst().orElse(null);
                model.setNation(dataEntity != null ? dataEntity.getFullName() : null);
            }
            model.setCertificatesNumber(exportVO.getCertificatesNumber());
            // 处理文化程度
            if (StringUtils.isNotEmpty(exportVO.getEducation())) {
                DictionaryDataEntity dataEntity = dataServiceList2.stream().filter(t -> exportVO.getEducation().equals(t.getFullName())).findFirst().orElse(null);
                model.setNation(dataEntity != null ? dataEntity.getFullName() : null);
            }
            // 处理生日
            if (StringUtils.isNotEmpty(exportVO.getBirthday())) {
                Date date = DateUtil.stringToDate(exportVO.getBirthday());
                model.setBirthday(date);
            }
            model.setTelePhone(exportVO.getTelePhone());
            model.setLandline(exportVO.getLandline());
            model.setEmail(exportVO.getEmail());
            model.setUrgentContacts(exportVO.getUrgentContacts());
            model.setUrgentTelePhone(exportVO.getUrgentTelePhone());
            model.setPostalAddress(exportVO.getPostalAddress());
            model.setSortCode(exportVO.getSortCode());
            // 入职时间
            if (StringUtils.isNotEmpty(exportVO.getEntryDate())) {
                Date date = DateUtil.stringToDate(exportVO.getEntryDate());
                model.setEntryDate(date);
            }
            // 设置状态
            if ("禁用".equals(exportVO.getEnabledMark())) {
                model.setEnabledMark(0);
            } else if ("正常".equals(exportVO.getEnabledMark())) {
                model.setEnabledMark(1);
            } else {
                model.setEnabledMark(2);
            }
            importModels.add(model);
        }

        List<UserEntity> entitys = JsonUtil.getJsonToList(importModels, UserEntity.class);
        //记录成功了几条
        int sum = 0;
        //记录第几条失败
        int num = 0;
        for (UserEntity entity : entitys) {
            entity.setHeadIcon("/api/file/Image/userAvatar/001.png");
            try {
                create(entity);
                sum++;
            } catch (Exception e) {
                UserExportVO exportVO = dataList.stream().filter(t -> entity.getAccount().equals(t.getAccount())).findFirst().orElse(null);
                exceptionList.add(exportVO);
                log.error("导入第" + (num + 1) + "条数据失败");
            }
        }
        UserImportVO vo = new UserImportVO();
        vo.setSnum(sum);
        if (exceptionList.size() > 0) {
            vo.setResultType(1);
            vo.setFailResult(JsonUtil.getJsonToList(exceptionList, UserExportExceptionVO.class));
            vo.setFnum(exceptionList.size());
            return vo;
        } else {
            vo.setResultType(0);
            return vo;
        }
    }

    @Override
    public void getOrganizeIdTree(String organizeId, StringBuffer organizeParentIdList) {
        OrganizeEntity entity = organizeService.getInfo(organizeId);
        if (Objects.nonNull(entity) && StringUtils.isNotEmpty(entity.getParentId())) {
            // 记录id
            organizeParentIdList.append(organizeId + ",");
            getOrganizeIdTree(entity.getParentId(), organizeParentIdList);
        }
    }

    @Override
    public DownloadVO exportExceptionData(List<UserExportVO> dataList) {
        DownloadVO vo = exportUtil("account,realName,gender,email,organizeId,managerId,positionId,roleId,sortCode,enabledMark,description,nation,nativePlace,entryDate,certificatesType,certificatesNumber,education,birthday,telePhone,landline,mobilePhone,urgentContacts,urgentTelePhone,postalAddress", "错误报告", dataList);
        return vo;
    }

    @Override
    public List<UserEntity> getUserName(List<String> id, Pagination pagination) {
        List<UserEntity> list = new ArrayList<>();
        id.removeAll(Collections.singleton(null));
        if (id.size() > 0) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            if (!StringUtils.isEmpty(pagination.getKeyword())) {
                queryWrapper.lambda().and(t -> t.like(UserEntity::getRealName, pagination.getKeyword()).or().like(UserEntity::getAccount, pagination.getKeyword()));
            }
            queryWrapper.lambda().in(UserEntity::getId, id);
            queryWrapper.lambda().select(UserEntity::getId, UserEntity::getRealName, UserEntity::getAccount);
            Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
            IPage<UserEntity> iPage = this.page(page, queryWrapper);
            return pagination.setData(iPage.getRecords(), iPage.getTotal());
        }
        return pagination.setData(list, list.size());
    }

    @Override
    public List<UserEntity> getListByRoleId(String roleId) {
        List<UserEntity> list = new ArrayList<>();
        // 根据roleId获取，用户与组织的关联对象集合
        userRelationService.getListByRoleId(roleId).forEach(u -> {
            list.add(this.getInfo(u.getUserId()));
        });
        return list;
    }


    @Override
    public Boolean delCurRoleUser(List<String> objectIdAll) {
        List<UserRelationEntity> data = userRelationService.getListByObjectIdAll(objectIdAll);
        List<String> userIds = data.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
        delCurUser(userIds);
        return true;
    }

    @Override
    public Boolean delCurUser(List<String> userIds) {
        for (String id : userIds) {
            userProvider.removeOnLine(id);
        }
        return true;
    }


    @Override
    public List<UserEntity> getList(List<String> orgIdList, String keyword) {
        // 得到用户关系表
        List<UserRelationEntity> listByObjectId = userRelationService.getListByOrgId(orgIdList);
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(UserEntity::getId, listByObjectId.stream().map(UserRelationEntity::getUserId).collect(Collectors.toList())).and(t -> t.like(UserEntity::getRealName, keyword).or().like(UserEntity::getAccount, keyword));
        return this.list(queryWrapper);
    }

    @Override
    public List<UserEntity> getListByOraganizetionId(String companyId) {
        if (StringUtils.isEmpty(companyId)) {
            return null;
        }
        List<String> underCompanyAllList = organizeService.getUnderOrganizations(companyId);
        return this.getList(underCompanyAllList, "");
    }

    private String getColumns(Integer key) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "账号");
        map.put(2, "姓名");
        map.put(3, "性别");
        map.put(4, "手机");
        map.put(5, "说明");
        map.put(6, "状态");
        map.put(7, "排序");
        map.put(8, "是否管理员");
        map.put(9, "锁定标志");
        map.put(10, "添加时间");
        map.put(11, "部门");
        return map.get(key);
    }

    /**
     * 判断上级是否直属主管的值是否为我的下属
     *
     * @param id
     * @param managerId
     * @param num
     */
    private boolean recursionSubordinates(String id, String managerId, int num) {
        UserEntity entity = getInfo(managerId);
        num++;
        if (entity != null && entity.getId().equals(id)) {
            return true;
        }
        if (num < 10) {
            if (entity != null) {
                return recursionSubordinates(id, entity.getManagerId(), num);
            }
            return false;
        } else {
            return false;
        }
    }

    /**
     * 设置默认密码
     *
     * @param
     * @return
     */
    @Override
    public String getDefaultPassword(String secretKey) {
        BaseSystemInfo baseSystemInfo = sysConfigService.getSysInfo();
        return Md5Util.getStringMd5(Md5Util.getStringMd5(baseSystemInfo.getDefaultPassword()).toLowerCase() + secretKey.toLowerCase());
    }

    /**
     * 根据角色id获取用户列表信息
     *
     * @param objectId
     * @return
     */
    @Override
    public List<UserEntity> getUserListByRoleId(String objectId) {
        List<UserRelationEntity> userRelationEntityList = userRelationService.getListByObjectId(objectId, PermissionConst.ROLE);
        List<String> userIds = new ArrayList<>();
        for (UserRelationEntity entity:userRelationEntityList) {
            userIds.add(entity.getUserId());
        }
        // 使用Stream API和toSet()进行去重
        Set<String> uniqueStrings = userIds.stream().collect(Collectors.toSet());

        // 如果需要，将Set转换回List
        List<String> uniqueStringList = new ArrayList<>(uniqueStrings);

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(UserEntity::getId, uniqueStringList);

        List<UserEntity> list = this.list(queryWrapper);
        return list;
    }

    /**
     * 根据菜单id获取用户列表信息
     *
     * @param authorizeEntityList
     * @return
     */
    @Override
    public List<UserEntity> getUserListByMenuId(List<AuthorizeEntity> authorizeEntityList) {
        List<UserEntity> list = new ArrayList<>();
        List<String> roleIds = new ArrayList<>();
        for (AuthorizeEntity authorizeEntity : authorizeEntityList) {
            QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().like(UserEntity::getRoleId, authorizeEntity.getObjectId());

            List<UserEntity> tempList = this.list(queryWrapper);
            list.addAll(tempList);
        }
        List<UserEntity> distinctList = list.stream().distinct().collect(Collectors.toList());
        return list;
    }

    @Override
    public List<UserEntity> getJurisDictionList(PaginationUser pagination) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean filterLastTime = false;
        String userId = userProvider.get().getUserId();
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(UserEntity::getId);

        //组织机构
        if (!StringUtils.isEmpty(pagination.getOrganizeId())) {
            List<String> orgIdList = organizeService.getUnderOrganizations(pagination.getOrganizeId());
//            获取数据权限组织id
            List<String> idDataPermission = userService.getIdDataPermission(pagination);
            orgIdList.retainAll(idDataPermission);

            PageHelper.startPage((int) pagination.getCurrentPage(), (int) pagination.getPageSize());
            // 用户id
            List<String> query = null;
            String dbSchema = "";
            // 判断是否为多租户
            if (Boolean.parseBoolean(configValueUtil.getMultiTenancy())) {
                dbSchema = DataSourceContextHolder.getDatasourceName();
            } else {
                dbSchema = dataSourceModel.getDbSchema();
            }
            if ("kingbasees".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryKingbase(pagination.getOrganizeId(), orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else if ("oracle".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryOracle(pagination.getOrganizeId(), orgIdList, pagination.getKeyword(), null, null);
            } else if ("dm8".equalsIgnoreCase(dataSourceModel.getDbType())) {
                query = userMapper.queryDm(pagination.getOrganizeId(), orgIdList, pagination.getKeyword(), dbSchema, null, null);
            } else {
                query = userMapper.query(pagination.getOrganizeId(), orgIdList, pagination.getKeyword(), null, null);
            }
            PageInfo pageInfo = new PageInfo(query);
            // 赋值分页参数
            pagination.setTotal(pageInfo.getTotal());
            pagination.setCurrentPage(pageInfo.getPageNum());
            pagination.setPageSize(pageInfo.getPageSize());
            if (pageInfo.getList().size() > 0) {
                // 存放返回结果
                List<UserEntity> entityList = new ArrayList<>(16);
                for (Object userIds : pageInfo.getList()) {
                    QueryWrapper<UserEntity> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.lambda().eq(UserEntity::getId, userIds);
                    entityList.add(this.getOne(queryWrapper1));
                }
                return entityList;
            } else {
                return new ArrayList<>();
            }
        }
        //关键字（账户、姓名、手机）
        if (!StringUtils.isEmpty(pagination.getKeyword())) {
            filterLastTime = true;
            queryWrapper.lambda().and(t -> t.like(UserEntity::getAccount, pagination.getKeyword()).or().like(UserEntity::getRealName, pagination.getKeyword()).or().like(UserEntity::getMobilePhone, pagination.getKeyword()));
        }
        //排序
        queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        if (filterLastTime) {
            queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
        }
        Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<UserEntity> iPage = this.page(page, queryWrapper);
        if (!iPage.getRecords().isEmpty()) {
            List<String> ids = iPage.getRecords().stream().map(m -> m.getId()).collect(Collectors.toList());
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, ids);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            if (filterLastTime) {
                queryWrapper.lambda().orderByDesc(UserEntity::getLastModifyTime);
            }
            iPage.setRecords(this.list(queryWrapper));
        }
//        数据权限控制
        if (!StringUtils.isNotEmpty(pagination.getOrganizeId())){
            iPage.setTotal(0);
        }
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public List<String> getIdDataPermission(PaginationUser pagination) {
        QueryWrapper<OrganizeEntity> queryWrapperOrganizeEntity = new QueryWrapper<>();
        //            不是超级管理员
        if (!userProvider.get().getIsAdministrator()) {
            Object companyAuth = authorizeService.getCondition(new AuthorizeConditionModel(queryWrapperOrganizeEntity, pagination.getMenuId(), "base_organize"));
            if (ObjectUtil.isEmpty(companyAuth)) {
                return new ArrayList<>();
            } else {
                queryWrapperOrganizeEntity = (QueryWrapper<OrganizeEntity>) companyAuth;
            }
        }
//            数据权限的公司部门id
        List<OrganizeEntity> organizeEntities = organizeMapper.selectList(queryWrapperOrganizeEntity);
        List<String> orgIdQuXian = new ArrayList<>();
//            第一次进入页面查询所有的数据
        if (!userProvider.get().getIsAdministrator() && ("1").equals(pagination.getOrganizeId())) {
//                全部公司部门id
            for (OrganizeEntity organizeEntity : organizeEntities) {
                orgIdQuXian.add(organizeEntity.getId());
            }
            return orgIdQuXian;
        } else {
//                遍历全部的数据权限id
            if (organizeEntities.size() == 1) {
//                    获取一个公司组织数据
                List<OrganizeEntity> allList2 = organizeService.getList();
                for (OrganizeEntity organizeEntity : allList2) {
                    if (organizeEntity.getOrganizeIdTree().contains(pagination.getOrganizeId())) {
                        orgIdQuXian.add(organizeEntity.getId());
                    }
                }
            } else {
                for (OrganizeEntity organizeEntity : organizeEntities) {
//                    获取公司或者组织下的值 pagination.getOrganizeId().equals(organizeEntity.getParentId())
                    if (organizeEntity.getOrganizeIdTree().contains(pagination.getOrganizeId())) {
                        orgIdQuXian.add(organizeEntity.getId());
                    }
                }
            }
            return orgIdQuXian;
        }
    }

    @Override
    public String getUserCompany(String userId) {
        UserEntity info = this.getInfo(userId);
        if (!ObjectUtil.isNull(info)) {
            OrganizeEntity companyListById = organizeService.getCompanyListById(info.getOrganizeId());
            return companyListById.getId();
        }
        return null;
    }
    @Override
    public List<UserListVO> getAuditList(PaginationUser pagination) throws BaseException {
        List<UserEntity> userList = this.getUserListByType(pagination,pagination.getAudit(), pagination.getOrganizeId(), false);

        List<UserListVO> list = new ArrayList<>();

        // 使用Lambda表达式过滤掉email为空的数据
        List<UserEntity> newEmailUserList = userList.stream()
                .filter(user -> StringUtils.isNotEmpty(user.getEmail()))
                .collect(Collectors.toList());

        // 使用Lambda表达式过滤掉mobilePhone为空的数据
        List<UserEntity> newMobilePhoneUserList = userList.stream()
                .filter(user -> StringUtils.isNotEmpty(user.getMobilePhone()))
                .collect(Collectors.toList());

        // 使用lambda表达式和Stream API找出重复的电子邮件
        Map<String, Long> emailCountMap = newEmailUserList.stream()
                .collect(Collectors.groupingBy(UserEntity::getEmail, Collectors.counting()));
        // 单独保存重复的电子邮件信息
        List<String> duplicateEmails = emailCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        // 使用lambda表达式和Stream API找出重复的手机号
        Map<String, Long> mobilePhoneCountMap = newMobilePhoneUserList.stream()
                .collect(Collectors.groupingBy(UserEntity::getMobilePhone, Collectors.counting()));
        // 单独保存重复的手机号信息
        List<String> duplicateMobilePhonels = mobilePhoneCountMap.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());


        for (UserEntity userEntity : userList) {
            UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class);
            // 时间小于当前时间则判断已解锁
            if (userVO.getEnabledMark() != 0) {
                if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) {
                    userVO.setEnabledMark(2);
                }
            }
            //获取组织
            String organizeStr = userRelationService.getAllOrganizeNameInfoById(userEntity.getId());
            userVO.setOrganize(organizeStr);
            //获取系统默认密码
            String defaultPassword = userService.getDefaultPassword(userEntity.getSecretkey());
            StringBuffer stringBuffer = new StringBuffer();
            //判断是都未修改初始密码
            if(StringUtils.isNull(userEntity.getChangePasswordDate()) || defaultPassword.equals(userEntity.getPassword())){
                stringBuffer.append("未修改初始密码");
            }
            //获取密码多久未修改
            int changPasswordDay = 0;
            if(StringUtils.isNull(userEntity.getChangePasswordDate())){
                changPasswordDay = DateUtil.getDiffDays(userEntity.getCreatorTime(),DateUtil.getNowDate());
            }else{
                changPasswordDay = DateUtil.getDiffDays(userEntity.getChangePasswordDate(),DateUtil.getNowDate());
            }
            if(changPasswordDay  > 30){
                stringBuffer.append(",定期未修改密码");
            }

            //判断是否长时间未登录
            if(StringUtils.isNull(userEntity.getLastLogTime()) || DateUtil.getDiffDays(userEntity.getLastLogTime(),DateUtil.getNowDate()) > 30){
                stringBuffer.append(",长期未登录");
            }

            //查询用户关系表中部门信息
            List<UserRelationEntity> relationOrganizeList = userRelationService.getListByUserIdAndObjectId(userEntity.getId(), userEntity.getOrganizeId(), PermissionConst.ORGANIZE);

            //查询用户关系表中角色信息
            String[] RoleIds = userEntity.getRoleId().split(",");
            boolean roleStatus = true;

            List<UserRelationEntity> relationRoleList = userRelationService.getListByUserIdAndObjType(userEntity.getId(), PermissionConst.ROLE);
            if(StringUtils.isNull(relationRoleList) || relationRoleList.size() < 1){
                roleStatus = false;
            }

            //查询第三方账户数据
            SynThirdInfoCrForm synThirdInfoCrForm = new SynThirdInfoCrForm();
            synThirdInfoCrForm.setThirdtype(1);
            synThirdInfoCrForm.setSynstate(1);
            synThirdInfoCrForm.setSysObjId(userEntity.getId());
            List<SynThirdInfoEntity> synThirdList = synThirdInfoService.getList(synThirdInfoCrForm);

            //判断账号是否异常 -用户部门/角色不存在、用户部门/角色关系不存、账户邮箱手机号重复、未关联第三方账户数据
            if(StringUtils.isNull(userEntity.getOrganizeId())){
                stringBuffer.append(",用户部门不存在");
            }
            if(StringUtils.isNull(userEntity.getRoleId())){
                stringBuffer.append(",用户角色不存在");
            }
            if(StringUtils.isNull(relationOrganizeList) || relationOrganizeList.size() < 1){
                stringBuffer.append(",用户部门关系不存在");
            }
            if(!roleStatus){
                stringBuffer.append(",用户角色关系不存在/异常");
            }
            if(StringUtils.isNull(synThirdList) || synThirdList.size() < 1){
                stringBuffer.append(",未关联第三方账户数据");
            }
            if(StringUtils.isNotEmpty(userEntity.getMobilePhone())){
                if(duplicateMobilePhonels.contains(userEntity.getMobilePhone())){
                    stringBuffer.append(",手机号重复");
                }

            }
            if(StringUtils.isNotEmpty(userEntity.getEmail())){
                if(duplicateEmails.contains(userEntity.getEmail())){
                    stringBuffer.append(",邮箱重复");
                }
            }
            userVO.setAuditResult(stringBuffer.toString());
            list.add(userVO);
        }
        return  list;
    }

//   public List<UserEntity> getUserListByType(PaginationUser pagination){
//       List<UserEntity> userList = new ArrayList<>();
//
//
//   }

    public List<UserEntity> getUserListByType(Pagination pagination,String type, String organizeId, Boolean flag) {
        // 定义变量判断是否需要使用修改时间倒序
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().select(UserEntity::getId);

        switch (type){
            case "1": //未修改初始密码
                queryWrapper.isNull("CHANGE_PASSWORD_DATE");
                break;
            case "2": //定期未修改密码
                Date frontDay = DateUtil.getFrontDay(DateUtil.getNowDate(), 30);
                queryWrapper.isNull("CHANGE_PASSWORD_DATE").or().lt("CHANGE_PASSWORD_DATE", frontDay);
                break;
            case "3": //长期未登录
                Date frontDay1 = DateUtil.getFrontDay(DateUtil.getNowDate(), 30);
                queryWrapper.isNull("LAST_LOGIN_TIME").or().lt("LAST_LOGIN_TIME", frontDay1);
                break;
            case "4": //用户部门不存在
                queryWrapper.isNull("ORGANIZE_ID");
                break;
            case "5": //用户角色不存在
                queryWrapper.isNull("ROLE_ID");
                break;
            case "6": //用户部门关系不存在
                queryWrapper.notExists("SELECT 1 FROM BASE_USER_RELATION bur WHERE bur.object_type = 'Organize' and base_user.id = bur.user_id AND " +
                        "base_user.ORGANIZE_ID = bur.OBJECT_ID");
                break;
            case "7": //用户角色关系不存在/异常
                queryWrapper.last(" where id not in(SELECT  distinct bu.id FROM BASE_USER bu inner join " +
                        "BASE_USER_RELATION bur WHERE" +
                        " bur.object_type = 'Role' and bu.id = bur.user_id) ORDER BY SORT_CODE ASC,CREATOR_TIME DESC");
                break;
            case "8": //未关联第三方账户数据
                queryWrapper.notExists("SELECT distinct 1 FROM base_sync_third_info bur WHERE base_user.id = bur.system_object_id AND " +
                        "bur.third_type = 1 AND bur.syn_state = 1");
                break;
            case "9": //手机号重复
                queryWrapper.last("where mobile_phone in(select mobile_phone  " +
                        "from base_user where mobile_phone is not null and mobile_phone != '' " +
                        "group by mobile_phone having count(mobile_phone) > 1 ) ORDER BY SORT_CODE ASC,CREATOR_TIME DESC");
                break;
            case "10": //邮箱重复
                queryWrapper.last("where email in(select email  from" +
                        " base_user where email is not null and email != '' " +
                        "group by email having count(email) > 1 ) ORDER BY SORT_CODE ASC,CREATOR_TIME DESC");
                break;
            default: //全部
//                userList = userService.getList(pagination, pagination.getOrganizeId(), false);
                break;
        }
        //排序
        if(!("7".equals(type) || "9".equals(type) || "10".equals(type))){
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
        }
        Page<UserEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<UserEntity> iPage = this.page(page, queryWrapper);

        if (!iPage.getRecords().isEmpty()) {
            List<String> ids = iPage.getRecords().stream().map(m -> m.getId()).collect(Collectors.toList());
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(UserEntity::getId, ids);
            queryWrapper.lambda().orderByAsc(UserEntity::getSortCode).orderByDesc(UserEntity::getCreatorTime);
            iPage.setRecords(this.list(queryWrapper));
        }
        return pagination.setData(iPage.getRecords(), iPage.getTotal());
    }
    @Override
    public String getUserCompanyShortName(String userId) {
        String userCompany = this.getUserCompany(userId);
        OrganizeEntity info = organizeService.getInfo(userCompany);
        OrganizeCrModel jsonToBean = JsonUtil.getJsonToBean(info.getPropertyJson(), OrganizeCrModel.class);
        if (!ObjectUtil.isNull(jsonToBean)) {
            return jsonToBean.getShortName();
        }
        return null;
    }
}
